import api from 'src/api'
import {getCookie,parseCookie} from 'util/util'
const state = {
  userId:'',
  avatar:'',
  userName:'',
  banner:''
}
const getters = {
  userId: state => state.userId,
  avatar: state => state.avatar,
  userName: state => state.userName,
  banner: state => state.banner 
}
const mutations = {
  SET_BANNER: (state, banner) => {
    state.banner = banner
  },
  SET_AVATAR:(state, avatar) => {
    state.avatar = avatar
  },
  SET_USERNAME:(state, userName)=>{
  	state.userName = userName
  },
  SET_USERID:(state, userId)=>{
  	state.userId = userId
  }
}
const actions = {
  getBanner ({ state, commit , dispatch},cookies) {
  	return  new Promise((resolve,reject)=>{
			api.get('/banner')
				  .then((res)=> {
			    	console.log("banner:"+res.data.banner)
			     	commit('SET_BANNER', res.data.banner)
				    resolve();
				  })
				  .catch((error)=>{
				  	console.log(error)
					 	reject(error)
			   });
		}).then(function(){
//			console.log('cookie: '+parseCookie(cookies,'UNION_TOKEN'))
//			if(parseCookie(cookies,'UNION_TOKEN')){
//				return dispatch('getUserInfo')
//			}else{
//				return Promise.resolve()
//			}
		})
  },
  getUserInfo({ state, commit }){
  	return new Promise(function(resolve,reject){
			api.get('/wx/user')
		  .then((res)=> {
		  	console.log(res)
		     if(res.error == 0){
		     }else{
		     	console.log(res.msg)
		     }
		     resolve()
		  })
		  .catch((error)=>{
		  	 reject(error)
	      });
  	}).then(function(){
  		return new Promise(function(resolve,reject){
  			api.get('/user/profile').then((res)=> {
		     if(res.error == 0){
		     	commit('SET_USERID', res.data.user_id)
          commit('SET_USERNAME', res.data.nickname);
          commit('SET_AVATAR', res.data.avatar)
		     }else{
		     	console.log(res.msg);
		     }
		     resolve();
			  })
			  .catch((error)=>{
			  	 reject(error)
		      });
	  		})
  	})
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}